package com.cpi.cornpp.version.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.version.exception.VersionException;
import com.cpi.cornpp.version.form.VersionForm;
import com.cpi.cornpp.version.services.VersionService;
import com.cpi.cornpp.version.view.VersionView;

public class SaveEditVersionAction extends Action {
	private static final String CUSTOM_EXCEPTION = "custom_exception";//$NON-NLS-1$
	private static final String SUCCESS_FORWARD = "toSuccess";
	private static final String FAILURE_FORWARD = "error";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws VersionException{
		VersionForm versionForm = null;
		VersionView versionView = null;
		VersionService versionService = null;
		HttpSession session = null;
		ActionForward forward = null;
		
		forward = mapping.findForward(FAILURE_FORWARD);
		session = request.getSession(false);
		
		try{
			
			if (form != null){
				versionView = new VersionView();
				versionService = new VersionService();
				versionForm = (VersionForm) form;
				
				versionView.setVersionId(versionForm.getVersionView().getVersionId());
				versionView.setShortName(versionForm.getVersionView().getShortName());
				versionView.setDescription(versionForm.getVersionView().getDescription());
				versionView.setActive(versionForm.getVersionView().isActive());
				
				versionService.updateVersion(versionView);
				
				forward = mapping.findForward(SUCCESS_FORWARD);
			}
			
		} catch (VersionException vee){
			session.setAttribute(CUSTOM_EXCEPTION, vee);
			throw vee;
		} catch (Exception e){
			VersionException vee=null;
			e.printStackTrace(System.out);
			vee= new VersionException(e , CornPPException.LAYER_ACTION,CornPPException.ACTION_LISTS);
			session.setAttribute(CUSTOM_EXCEPTION, vee);
			throw vee;
		}
		
		return forward;
	}
}